"""
auth:xgt-python
datetime:2021/11/22
突破京东反爬
"""
import time
import csv
from selenium import webdriver


def get_product(word):
    """搜素商品"""
    driver.find_element_by_css_selector('#key').send_keys(word)
    driver.find_element_by_css_selector('#search > div > div.form > button ').click()

    driver.implicitly_wait(10)  # 渲染页面
    driver.maximize_window()  # 最大化浏览器


def parse_data():
    """解析商品数据"""
    lis = driver.find_elements_by_css_selector('.gl-item')  # 所有的li标签

    for li in lis:
        try:
            name = li.find_element_by_css_selector('div.p-name a em').text  # 商品名字
            name.replace('京东超市', '').replace('"', '').replace('\n', '')

            price = li.find_element_by_css_selector('div.p-price strong i').text + "元"  # 商品价格
            deals = li.find_element_by_css_selector('div.p-commit strong a').text  # 评价数量
            title = li.find_element_by_css_selector('span.J_im_icon a').text  # 店铺名字
            print(name, price, deals, title, sep=' | ')

            # 数据保存
            with open('resource.csv', mode='a', encoding='utf-8', newline="") as file:
                csv_write = csv.writer(file, )
                csv_write.writerow([name, price, deals, title])
        except:
            pass


def get_next():
    """找到下一页标签点击，进入到下一页"""
    driver.find_element_by_css_selector('#J_bottomPage > span.p-num > a.pn-next > em').click()


def drop_down():
    """模拟任务滚动鼠标滚轮,加载所有数据"""
    for x in range(1, 11, 2):  # 控制滚动的次数   滚动5次
        time.sleep(0.5)
        j = x / 10  # 按照分数位滑动距离
        js = "document.documentElement.scrollTop = document.documentElement.scrollHeight * %s" % j
        driver.execute_script(js)


keyword = input('请输入你要搜素的关键字:')

# 实例化一个浏览器对象
driver = webdriver.Chrome()
driver.get('https://www.jd.com/')

get_product(keyword)

for page in range(1, 101):
    drop_down()
    parse_data()
    get_next()

input()
driver.quit()  # 关闭浏览器
